#include "preHeader.h"
#include "DBPServerMaster.h"
#include "DBPServer.h"
#include "Session/GameListener.h"
#include "Session/GameSessionHandler.h"

DBPServerMaster::DBPServerMaster()
{
}

DBPServerMaster::~DBPServerMaster()
{
}

bool DBPServerMaster::InitSingleton()
{
	GameSessionHandler::newInstance();
	MysqlDatabasePool::newInstance();
	GameListener::newInstance();
	DBPServer::newInstance();
	return true;
}

void DBPServerMaster::FinishSingleton()
{
	GameSessionHandler::deleteInstance();
	MysqlDatabasePool::deleteInstance();
	GameListener::deleteInstance();
	DBPServer::deleteInstance();
}

bool DBPServerMaster::InitDBPool()
{
	const auto& cfg = GetConfig();

	if (!sMysqlDatabasePool.InitCharDB(
		cfg.GetString("CHAR_DB", "HOST", "127.0.0.1"),
		cfg.GetInteger("CHAR_DB", "PORT", 3306),
		cfg.GetString("CHAR_DB", "USER", "app"),
		cfg.GetString("CHAR_DB", "PASSWORD", "123456"),
		cfg.GetString("CHAR_DB", "DATABASE", "mmorpg_char")))
	{
		return false;
	}

	if (!sMysqlDatabasePool.InitLogDB(
		cfg.GetString("LOG_DB", "HOST", "127.0.0.1"),
		cfg.GetInteger("LOG_DB", "PORT", 3306),
		cfg.GetString("LOG_DB", "USER", "app"),
		cfg.GetString("LOG_DB", "PASSWORD", "123456"),
		cfg.GetString("LOG_DB", "DATABASE", "mmorpg_log")))
	{
		return false;
	}

	return true;
}

bool DBPServerMaster::LoadDBData()
{
	return true;
}

bool DBPServerMaster::StartServices()
{
	if (!sGameListener.Start()) {
		ELOG("--- sGameListener.Start() failed.");
		return false;
	}

	if (!sDBPServer.Start()) {
		ELOG("--- sDBPServer.Start() failed.");
		return false;
	}

	return true;
}

void DBPServerMaster::StopServices()
{
	sGameListener.Stop();
	sDBPServer.Stop();
}

void DBPServerMaster::Tick()
{
	sMysqlDatabasePool.GetCharDB()->CheckConnections();
	sMysqlDatabasePool.GetLogDB()->CheckConnections();
}

std::string DBPServerMaster::GetConfigFile()
{
	return "etc/DBPServer.conf";
}

size_t DBPServerMaster::GetDeferAsyncServiceCount()
{
	return GetConfig().GetInteger("OTHER", "DEFER_ASYNC_THREAD", 1);
}

size_t DBPServerMaster::GetAsyncServiceCount()
{
	return GetConfig().GetInteger("OTHER", "ASYNC_THREAD", 1);
}

size_t DBPServerMaster::GetIOServiceCount()
{
	return GetConfig().GetInteger("OTHER", "IO_THREAD", 1);
}
